<template>
  <div class="invite_box">
    <van-nav-bar title="邀请好友" left-arrow fixed @click-left="onClickLeft" />
    
    <!-- 轮播图 -->
    <div class="swiper" id="swiper1" v-if="background && background.length > 0">
      <van-swipe class="my-swipe" :autoplay="0" indicator-color="#F32A23" @change="onSwipeChange">
        <van-swipe-item v-for="(item, index) in background" :key="index">
          <div class="swipe_item_img" :id="'posterHtml' + index"
               @touchstart="handleImageTouchStart" 
               @touchend="handleImageTouchEnd"
               @touchmove="handleImageTouchMove" 
               @contextmenu.prevent="preventContextMenu">
            <img class="itemImg" :src="item" alt="" crossorigin="anonymous" />
            <vue-qr 
              :text="codeText" 
              class="swipe_bottom" 
              :margin="10"
            ></vue-qr>
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>
    
    <!-- 底部 -->
    <div class="invite_bom">
      <div class="invite_bom_item" 
           @touchstart="handleButtonTouchStart" 
           @touchend="handleButtonTouchEnd"
           @touchmove="handleButtonTouchMove" 
           @contextmenu.prevent="preventContextMenu">
        <div class="pic">
          <img class="pic_one" src="../../images/mine/xiazai.png" alt="" />
          <img class="pic_two" :src="pics[currentPicIndex]" alt="" v-if="pics[currentPicIndex]" />
        </div>
        <div class="text">长按保存</div>
      </div>
    </div>
  </div>
</template>

<script>
import { INVITE_CONFIG } from "@/api/mine";
import html2canvas from "html2canvas";
import VueQr from "vue-qr";

export default {
  name: "HomeView",
  components: { VueQr },
  data() {
    return {
      invite: {},
      background: [],
      codeText: "",
      pics: [],
      currentPicIndex: 0,
      touchTimer: null,
      isLongPress: false,
      isSaving: false,
      generatedPosters: new Set(),
      isGenerating: false,
      touchStartX: 0,
      touchStartY: 0,
      isSwiping: false,
      longPressThreshold: 800,
    };
  },
  mounted() {
    window.scrollTo(0, 0);
    this.inviteConfig();
  },
  methods: {
    async inviteConfig() {
      try {
        const res = await this.$http.get(INVITE_CONFIG);
        this.invite = res.data;
        this.background = res.data.background_list;
        this.codeText = res.data.invite_url;
        
        this.$nextTick(() => {
          setTimeout(() => {
            this.createPoster();
          }, 500);
        });
        
      } catch (error) {
        this.$toast('加载失败，请重试');
      }
    },

    async createPoster() {
      if (this.isGenerating) {
        return;
      }
      
      this.isGenerating = true;
      
      try {
        const promises = this.background.map(async (item, index) => {
          if (this.generatedPosters.has(index)) {
            return;
          }
          
          await this.$nextTick();
          const domObj = document.getElementById("posterHtml" + index);
          
          if (!domObj) {
            return;
          }

          await new Promise(resolve => setTimeout(resolve, 300));

          const canvas = await html2canvas(domObj, {
            useCORS: true,
            allowTaint: false,
            logging: false,
            scale: 2,
            width: domObj.scrollWidth,
            height: domObj.scrollHeight,
            onclone: (clonedDoc) => {
              const clonedElement = clonedDoc.getElementById("posterHtml" + index);
              if (clonedElement) {
                clonedElement.style.display = "block";
                clonedElement.style.visibility = "visible";
              }
            }
          });

          const dataUrl = canvas.toDataURL("image/png", 1.0);
          
          this.$set(this.pics, index, dataUrl);
          this.generatedPosters.add(index);
          
        });

        await Promise.all(promises);
        
        
      } catch (error) {
        this.$toast('生成海报失败');
      } finally {
        this.isGenerating = false;
      }
    },

    onSwipeChange(index) {
      this.currentPicIndex = index;
      this.generateCurrentPoster(index);
    },

    async generateCurrentPoster(index) {
      if (!this.pics[index] && !this.generatedPosters.has(index)) {
        await this.generateSinglePoster(index);
      }
    },

    async generateSinglePoster(index) {
      try {
        const domObj = document.getElementById("posterHtml" + index);
        if (!domObj) {
          return;
        }

        await new Promise(resolve => setTimeout(resolve, 200));

        const canvas = await html2canvas(domObj, {
          useCORS: true,
          allowTaint: false,
          scale: 2,
          width: domObj.scrollWidth,
          height: domObj.scrollHeight,
          onclone: (clonedDoc) => {
            const clonedElement = clonedDoc.getElementById("posterHtml" + index);
            if (clonedElement) {
              clonedElement.style.display = "block";
            }
          }
        });

        const dataUrl = canvas.toDataURL("image/png", 1.0);
        this.$set(this.pics, index, dataUrl);
        this.generatedPosters.add(index);
        
      } catch (error) {
        // 生成失败时静默处理
      }
    },

    handleImageTouchStart(e) {
      // 记录触摸开始位置
      this.touchStartX = e.touches[0].clientX;
      this.touchStartY = e.touches[0].clientY;
      this.isSwiping = false;
      
      // 启动长按计时器
      this.touchTimer = setTimeout(() => {
        if (!this.isSwiping) {
          this.isLongPress = true;
          this.saveImage();
        }
      }, this.longPressThreshold);
    },

    handleImageTouchMove(e) {
      if (!this.touchStartX || !this.touchStartY) return;
      
      const touchX = e.touches[0].clientX;
      const touchY = e.touches[0].clientY;
      
      const deltaX = Math.abs(touchX - this.touchStartX);
      const deltaY = Math.abs(touchY - this.touchStartY);
      
      // 如果移动距离大于阈值，认为是滑动，取消长按
      if (deltaX > 5 || deltaY > 5) {
        this.isSwiping = true;
        if (this.touchTimer) {
          clearTimeout(this.touchTimer);
          this.touchTimer = null;
        }
      }
      
      // 不阻止默认行为，允许页面滚动和轮播滑动
    },
    handleImageTouchEnd(e) {
      if (this.touchTimer) {
        clearTimeout(this.touchTimer);
        this.touchTimer = null;
      }
      
      this.touchStartX = 0;
      this.touchStartY = 0;
      this.isSwiping = false;
    },

    handleButtonTouchStart(e) {
      e.preventDefault();
      e.stopPropagation();
      
      this.isLongPress = false;
      
      this.touchTimer = setTimeout(() => {
        this.isLongPress = true;
        this.saveImage();
      }, this.longPressThreshold);
    },
    handleButtonTouchMove(e) {
      e.preventDefault();
      e.stopPropagation();
      this.handleButtonTouchEnd(e);
    },

    handleButtonTouchEnd(e) {
      e.preventDefault();
      e.stopPropagation();
      
      if (this.touchTimer) {
        clearTimeout(this.touchTimer);
        this.touchTimer = null;
      }
    },

    async saveImage() {
      if (this.isSaving) {
        this.$toast('正在保存中，请稍候');
        return;
      }

      this.isSaving = true;
      const saveIndex = this.currentPicIndex;

      try {
        if (!this.pics[saveIndex]) {
          this.$toast('生成图片中，请稍候...');
          await this.generateSinglePoster(saveIndex);
          
          if (!this.pics[saveIndex]) {
            throw new Error(`海报 ${saveIndex} 生成失败`);
          }
        }

        const imageUrl = this.pics[saveIndex];
        
        const link = document.createElement('a');
        link.href = imageUrl;
        link.download = `邀请海报_${saveIndex + 1}_${Date.now()}.png`;
        link.style.display = 'none';
        
        document.body.appendChild(link);
        link.click();
        
        setTimeout(() => {
          document.body.removeChild(link);
          if (link.href.startsWith('blob:')) {
            URL.revokeObjectURL(link.href);
          }
        }, 100);

        this.$toast('图片保存成功');

      } catch (error) {
        this.$toast('保存失败，请重试');
      } finally {
        setTimeout(() => {
          this.isSaving = false;
        }, 2000);
      }
    },

    preventContextMenu(e) {
      e.preventDefault();
      return false;
    },

    onClickLeft() {
      this.$router.back();
    },

    downLoadApp() {
      window.open(this.codeText, "_blank");
    },
  },
};
</script>

<style lang="scss" scoped>
.invite_box {
  padding-top: 46px;
  background: #f2f4f5;
  min-height: calc(100vh - 46px);

  ::v-deep .van-nav-bar .van-icon {
    color: #333333;
  }

  ::v-deep .van-nav-bar__arrow {
    font-size: 20px;
  }
}

.my-swipe {
  padding-top: 0.32rem;
  position: relative;
  overflow: hidden;
  padding-bottom: 0.6rem;
  margin-bottom: 2rem;
}

::v-deep .van-swipe__indicator {
  width: 0.12rem;
  height: 0.12rem;
  background: #ababab;
}

.swipe_item_img {
  display: flex;
  width: 90%;
  height: 100%;
  margin: 0 auto;
  justify-content: center;
  position: relative;
  -webkit-tap-highlight-color: transparent;
  
  touch-action: auto;

  .itemImg {
    width: 100%;
    height: 100%;
    object-fit: contain;
    // pointer-events: none;
  }

  .swipe_bottom {
    width: 30%;
    position: absolute;
    bottom: 6%;
    z-index: 1;
    left: 50%;
    transform: translateX(-50%);
    // pointer-events: none;
  }
}

.swipe_item_img img {
  width: 100%;
}

.invite_bom {
  height: 2rem;
  width: 100%;
  padding: 0.24rem;
  box-sizing: border-box;
  background: #fff;
  display: flex;
  position: fixed;
  bottom: 0;

  &_item {
    width: 100%;
    text-align: center;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 0.26rem;
    color: #333333;
    line-height: 0.34rem;
    font-style: normal;

    .text {
      margin-top: 0.2rem;
    }

    .pic {
      position: relative;
      height: 0.72rem;

      img {
        width: 0.72rem;
        height: 0.72rem;
        margin-bottom: 0.12rem;
        margin-right: -0.72rem;
      }

      .pic_one {
        width: 0.72rem;
        height: 0.72rem;
        position: absolute;
        top: 0;
        left: calc(50% - 0.31rem);
      }

      .pic_two {
        position: absolute;
        top: 0;
        z-index: 999;
        opacity: 0;
        left: calc(50% - 0.31rem);
      }
    }
  }
}

.invite_bom_item {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  touch-action: manipulation;
}

.swipe_item_img {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  touch-action: auto;
}
</style>